import 'package:meco/common/index.dart';
import 'package:meco/common/models/recommended_video_interaction_model.dart';
import 'package:meco/common/models/recommended_video_model.dart';
import 'package:meco/common/data/repositories/recommended_video_repository.dart';
import 'package:meco/common/data/services/database_service.dart';

/// 定义一个接口，用于接收视频交互状态更新
abstract class VideoInteractionObserver {
  void onVideoLikeStatusChanged(int userId, int videoId, bool isLiked);
  void onVideoFavoriteStatusChanged(int userId, int videoId, bool isFavorited);
}

class VideoInteractionRepository {
  final DatabaseService _databaseService = DatabaseService();
  final RecommendedVideoRepository _videoRepository =
      RecommendedVideoRepository();

  // 静态观察者列表，用于通知状态变化
  static final List<VideoInteractionObserver> _observers = [];

  // 添加观察者
  static void addObserver(VideoInteractionObserver observer) {
    if (!_observers.contains(observer)) {
      _observers.add(observer);
    }
  }

  // 移除观察者
  static void removeObserver(VideoInteractionObserver observer) {
    _observers.remove(observer);
  }

  // 通知点赞状态变化
  void _notifyLikeStatusChanged(int userId, int videoId, bool isLiked) {
    for (var observer in _observers) {
      observer.onVideoLikeStatusChanged(userId, videoId, isLiked);
    }
  }

  // 通知收藏状态变化
  void _notifyFavoriteStatusChanged(int userId, int videoId, bool isFavorited) {
    for (var observer in _observers) {
      observer.onVideoFavoriteStatusChanged(userId, videoId, isFavorited);
    }
  }

  // 表名
  final String _likesTableName = 'video_likes';
  final String _favoritesTableName = 'video_favorites';

  // 点赞视频
  Future<bool> likeVideo(int userId, int videoId) async {
    final db = await _databaseService.database;
    final now = DateTime.now();

    try {
      // 检查是否已点赞
      final exists = await hasLiked(userId, videoId);
      if (exists) {
        return true; // 已经点赞过了
      }

      // 创建点赞记录
      final like = VideoLike(
        userId: userId,
        videoId: videoId,
        createdAt: now,
        updatedAt: now,
      );

      final id = await db.insert(_likesTableName, like.toJson());

      if (id > 0) {
        // 更新视频的点赞数
        await _videoRepository.incrementLikeCount(videoId);
        // 通知观察者点赞状态变化
        _notifyLikeStatusChanged(userId, videoId, true);
        return true;
      }

      return false;
    } catch (e) {
      print('点赞视频失败: $e');
      return false;
    }
  }

  // 取消点赞视频
  Future<bool> unlikeVideo(int userId, int videoId) async {
    final db = await _databaseService.database;

    try {
      // 删除点赞记录
      final count = await db.delete(
        _likesTableName,
        where: 'user_id = ? AND video_id = ?',
        whereArgs: [userId, videoId],
      );

      if (count > 0) {
        // 更新视频的点赞数
        await _videoRepository.decrementLikeCount(videoId);
        // 通知观察者点赞状态变化
        _notifyLikeStatusChanged(userId, videoId, false);
        return true;
      }

      return false;
    } catch (e) {
      print('取消点赞视频失败: $e');
      return false;
    }
  }

  // 检查用户是否已点赞视频
  Future<bool> hasLiked(int userId, int videoId) async {
    final db = await _databaseService.database;

    final List<Map<String, dynamic>> result = await db.query(
      _likesTableName,
      where: 'user_id = ? AND video_id = ?',
      whereArgs: [userId, videoId],
      limit: 1,
    );

    return result.isNotEmpty;
  }

  // 收藏视频
  Future<bool> favoriteVideo(int userId, int videoId) async {
    final db = await _databaseService.database;
    final now = DateTime.now();

    try {
      // 检查是否已收藏
      final exists = await hasFavorited(userId, videoId);
      if (exists) {
        return true; // 已经收藏过了
      }

      // 创建收藏记录
      final favorite = VideoFavorite(
        userId: userId,
        videoId: videoId,
        createdAt: now,
        updatedAt: now,
      );

      final id = await db.insert(_favoritesTableName, favorite.toJson());

      if (id > 0) {
        // 更新视频的收藏数
        await _videoRepository.incrementFavoriteCount(videoId);
        // 通知观察者收藏状态变化
        _notifyFavoriteStatusChanged(userId, videoId, true);
        return true;
      }

      return false;
    } catch (e) {
      print('收藏视频失败: $e');
      return false;
    }
  }

  // 取消收藏视频
  Future<bool> unfavoriteVideo(int userId, int videoId) async {
    final db = await _databaseService.database;

    try {
      // 删除收藏记录
      final count = await db.delete(
        _favoritesTableName,
        where: 'user_id = ? AND video_id = ?',
        whereArgs: [userId, videoId],
      );

      if (count > 0) {
        // 更新视频的收藏数
        await _videoRepository.decrementFavoriteCount(videoId);
        // 通知观察者收藏状态变化
        _notifyFavoriteStatusChanged(userId, videoId, false);
        return true;
      }

      return false;
    } catch (e) {
      print('取消收藏视频失败: $e');
      return false;
    }
  }

  // 检查用户是否已收藏视频
  Future<bool> hasFavorited(int userId, int videoId) async {
    final db = await _databaseService.database;

    final List<Map<String, dynamic>> result = await db.query(
      _favoritesTableName,
      where: 'user_id = ? AND video_id = ?',
      whereArgs: [userId, videoId],
      limit: 1,
    );

    return result.isNotEmpty;
  }

  // 获取用户收藏的所有视频ID
  Future<List<int>> getUserFavoriteVideoIds(int userId) async {
    final db = await _databaseService.database;

    final List<Map<String, dynamic>> maps = await db.query(
      _favoritesTableName,
      columns: ['video_id'],
      where: 'user_id = ?',
      whereArgs: [userId],
    );

    return maps.map((map) => map['video_id'] as int).toList();
  }

  // 获取用户点赞的所有视频ID
  Future<List<int>> getUserLikedVideoIds(int userId) async {
    final db = await _databaseService.database;

    final List<Map<String, dynamic>> maps = await db.query(
      _likesTableName,
      columns: ['video_id'],
      where: 'user_id = ?',
      whereArgs: [userId],
    );

    return maps.map((map) => map['video_id'] as int).toList();
  }

  // 获取用户收藏的视频
  Future<List<RecommendedVideo>> getFavoritedVideos(int userId) async {
    try {
      final db = await _databaseService.database;
      final List<Map<String, dynamic>> maps = await db.rawQuery(
        '''
        SELECT v.* FROM recommended_videos v
        INNER JOIN video_favorites f ON v.id = f.video_id
        WHERE f.user_id = ?
        ORDER BY f.created_at DESC
      ''',
        [userId],
      );

      return List.generate(
        maps.length,
        (i) => RecommendedVideo.fromJson(maps[i]),
      );
    } catch (e) {
      print('获取用户收藏视频错误: $e');
      return [];
    }
  }

  // 获取用户点赞的视频
  Future<List<RecommendedVideo>> getLikedVideos(int userId) async {
    try {
      final db = await _databaseService.database;
      final List<Map<String, dynamic>> maps = await db.rawQuery(
        '''
        SELECT v.* FROM recommended_videos v
        INNER JOIN video_likes l ON v.id = l.video_id
        WHERE l.user_id = ?
        ORDER BY l.created_at DESC
      ''',
        [userId],
      );

      return List.generate(
        maps.length,
        (i) => RecommendedVideo.fromJson(maps[i]),
      );
    } catch (e) {
      print('获取用户点赞视频错误: $e');
      return [];
    }
  }
}
